import { memo, useCallback } from 'react';
import type { ReactNode, FC } from 'react';
import { RankingItemWrapper } from './style';
import { formatSongIds, getImgOnSize } from '@/utils/format';
import { useAppDispatch } from '@/store/hooks';
import { changeSongs, fetchSongDetail } from '@/views/player/store/player';
import { getSongDetail } from '@/service';
import { Link } from 'react-router-dom';
import { fetchRankDetail } from '../../../ranking/store/rank';
interface IProps {
  children?: ReactNode;
  item: any;
}

const TopRankingItem: FC<IProps> = (props) => {
  const { item } = props;
  const dispatch = useAppDispatch();
  // 切换目前的歌曲
  const handlePlayClick = useCallback((ids: number) => {
    dispatch(fetchSongDetail({ ids, play: true }));
  }, []);
  async function handleSongsClick() {
    const ids = formatSongIds(item.trackIds);
    const allSongs: any = await getSongDetail(ids);
    dispatch(changeSongs(allSongs.songs));
  }

  function handleMoreClick(): void {
    dispatch(fetchRankDetail(item.id));
    window.scrollTo(0, 0);
  }

  return (
    <RankingItemWrapper>
      <div className="rank-top">
        <div className="img">
          <Link to={'/discover/ranking'} onClick={handleMoreClick}>
            <img src={getImgOnSize(item.coverImgUrl, 80)} />
            <a className="sprite_cover imgCover"></a>
          </Link>
        </div>
        <div className="detail">
          <Link to={'/discover/ranking'} onClick={handleMoreClick}>
            <h3>{item.name}</h3>
          </Link>
          <div className="icon">
            <a className="sprite_02 f-a" onClick={handleSongsClick}></a>
            <a className="sprite_02 s-a" href="javascript:void(0)"></a>
          </div>
        </div>
      </div>
      {/* 榜单列表 */}
      <div className="list">
        {item.tracks.slice(0, 10).map((track: any, index: number) => {
          return (
            <div className="track" key={index}>
              <span>{index + 1}</span>
              <a>{track.name}</a>
              <div className="oper">
                <a
                  className="sprite_02 play"
                  title="播放"
                  href="javascript:void(0)"
                  onClick={() => handlePlayClick(track.id)}
                ></a>
                <a
                  className="icons addList"
                  title="添加到播放列表"
                  onClick={() => {
                    dispatch(fetchSongDetail({ ids: track.id, play: false }));
                  }}
                ></a>
                <a className="sprite_02 favorite" title=""></a>
              </div>
            </div>
          );
        })}
      </div>
      <div className="more">
        <Link to={'/discover/ranking'} onClick={handleMoreClick}>
          查看更多{'>'}
        </Link>
      </div>
    </RankingItemWrapper>
  );
};

export default memo(TopRankingItem);
